﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace WindMill.Models
{
    public class SimpleRoleProvider : RoleProvider
    {
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            var ctx = new EDMSeguranca();

            var papeis = ctx.Papeis.Where(c => roleNames.Contains(c.Descricao));

            try
            {
                var ids = usernames.Select(c => Convert.ToInt32(c));

                foreach (var i in ids)
                {

                    foreach (var p in papeis)
                    {
                        var pu = new PapelUsuario();

                        pu.IdPapel = p.Id;
                        pu.IdUsuario = i;
                        ctx.PapeisUsuarios.Add(pu);
                    }
                }
                ctx.SaveChanges();
            }
            catch (FormatException ex)
            {
                   
            }               
        }

        public override string ApplicationName
        {
            get
            {
                return "WindMill";
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            var ctx = new EDMSeguranca();

            ctx.Papeis.Add(new Papel() { Descricao = roleName });

            ctx.SaveChanges();            
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            var ctx = new EDMSeguranca();

            var papel = ctx.Papeis.FirstOrDefault(c => c.Descricao.Equals(roleName));

            if (papel == null)
                throw new ArgumentOutOfRangeException("Nenhum papel encontrado");

            if (throwOnPopulatedRole && papel.PapeisUsuarios.Any())
                throw new InvalidOperationException("O papel possui usuários atrelados a ele");
            else
                ctx.PapeisUsuarios.RemoveRange(ctx.PapeisUsuarios.Where(c=>c.IdPapel == papel.Id));

            ctx.Papeis.Remove(papel);

            ctx.SaveChanges();

            return true;
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            var ctx = new EDMSeguranca();

            var usuarios = ctx.Papeis.Where(c => c.Descricao.Equals(roleName)).SelectMany(c => c.PapeisUsuarios).Where(c => c.TB_USUARIO.Nome.Contains(usernameToMatch)).Select(c => c.TB_USUARIO).Distinct();

            return usuarios.Select(c => c.Id.ToString()).ToArray();
        }

        public override string[] GetAllRoles()
        {
            var ctx = new EDMSeguranca();

            return ctx.Papeis.Select(c => c.Descricao).ToArray();
        }

        public override string[] GetRolesForUser(string username)
        {
            var ctx = new EDMSeguranca();

            return ctx.PapeisUsuarios.Where(c=>c.IdUsuario.ToString().Equals(username)).Select(c=>c.Papel.Descricao).ToArray();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            var ctx = new EDMSeguranca();

            return ctx.Papeis.Where(c => c.Descricao.Equals(roleName)).SelectMany(c => c.PapeisUsuarios).Select(c => c.IdUsuario.ToString()).ToArray();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            var ctx = new EDMSeguranca();

            var idPapel = ctx.Papeis.Where(c => c.Descricao.Equals(roleName)).Select(c => c.Id).FirstOrDefault();

            if (idPapel == null)
                throw new InvalidOperationException("Papel não existe");

            return ctx.PapeisUsuarios.Count(c => c.IdPapel == idPapel && c.IdUsuario.ToString().Equals(username)) > 0;
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            var ctx = new EDMSeguranca();

            var papeisUsuarios = ctx.PapeisUsuarios.Include("Papel").Where(c => usernames.Contains(c.IdUsuario.ToString())).ToList();

            foreach (var p in papeisUsuarios)
            {
                if (roleNames.Contains(p.Papel.Descricao))
                {
                    ctx.PapeisUsuarios.Remove(p);
                }
            }

            ctx.SaveChanges();            
        }

        public override bool RoleExists(string roleName)
        {
            var ctx = new EDMSeguranca();

            var idPapel = ctx.Papeis.FirstOrDefault(c => c.Descricao.Equals(roleName));

            return idPapel != null;
        }
    }
}